#!/bin/bash
# Copyright 2025 The Lynx Authors. All rights reserved.
# Licensed under the Apache License Version 2.0 that can be found in the
# LICENSE file in the root directory of this source tree.


CURRENT_PATH="$(dirname "$(realpath "$0")")"
VENV_PATH=$CURRENT_PATH/../../.venv
LOCK_DIR=$CURRENT_PATH/../../.venv.lock
LOCK_TIMEOUT=300 # 5 min
PACKAGE_TO_IMPORT="yaml, requests"
PACKAGE_TO_INSTALL="PyYAML requests"
USE_VENV=false

check_requirements_or_install_if_missing() {
  python3 -c "import $PACKAGE_TO_IMPORT"
  if [ $? -eq 0 ]; then
      echo "All requirements installed"
  else
      echo "Some requirements are not installed"
      pip3 install $PACKAGE_TO_INSTALL
      if [ $? -eq 0 ]; then
          echo "All requirements installed successfully"
      else
          echo "Some requirements installation failed, please install them manually."
          exit 1
      fi
  fi
}

try_lock_by_dir() {
    if mkdir $LOCK_DIR; then
        echo $$ > "$LOCK_DIR/pid"
        echo "lock success"
        return 0
    else
        echo "lock failed"
        return 1
    fi
}

try_unlock_by_dir() {
    if [ -d "${LOCK_DIR}" ]; then
        local pid
        pid=$(cat "${LOCK_DIR}/pid" 2>/dev/null)
        if [ "$pid" = "$$" ]; then
            rm -rf "${LOCK_DIR}"
            return 0
        else
            echo "Can not release the lock not belong to current process" >&2
            return 1
        fi
    else
        echo "Lock dir is not exist" >&2
        return 1
    fi
}

python3 -c "import $PACKAGE_TO_IMPORT"
if [ $? -eq 0 ]; then
    echo "All requirements installed"
else
    echo "Some requirements are not installed, try to use venv $VENV_PATH"
    USE_VENV=true

    wait_for_lock_count=0
    while true; do
        try_lock_by_dir
        if [ $? -eq 0 ]; then
            break
        fi
        echo "wait for other vpython process to complete the init process"
        sleep 1
        wait_for_lock_count=$((wait_for_lock_count + 1))
        if [ $wait_for_lock_count -gt $LOCK_TIMEOUT ]; then
            echo "TIMEOUT: wait for other vpython process to complete the init process timeout, maybe other process faces some unexpected issue? "
            exit 1
        fi
    done

    # make sure to release the lock when exit by external
    trap try_unlock_by_dir SIGINT SIGTERM

    if [ -d $VENV_PATH ]; then
        echo "venv already exists, reuse it"
    else
        echo "venv not exists, create it"
        python3 -m venv $VENV_PATH
    fi
    source $VENV_PATH/bin/activate
    check_requirements_or_install_if_missing

    # break when unlock with any error
    set -e

    try_unlock_by_dir
fi

set -e

PYTHON_PATH=$(which python3)

"$PYTHON_PATH" "$@"

if [ $USE_VENV = true ]; then
    echo "deactivate venv"
    deactivate
fi

